<template>
    <Editor v-model="obj.html" :init="init" tinymceScriptSrc="/tinymce/tinymce.min.js" />
</template>

<script setup>
    import { getCurrentInstance, watch, reactive } from 'vue'
    import Editor from '@tinymce/tinymce-vue'
    let { proxy } = getCurrentInstance()
    const emit = defineEmits(['update:value']) //此处要完全对应，采用固定的update:prop属性
    const props = defineProps({
        value: { type: String, default: "", require: true },
        height: { type: [Number, String], required: false, default: 360 },
        width:  { type: [Number, String], required: false, default: '100%' },
        readOnly: { type: Boolean, default: false },
        placeholder: { type: String, default: "在这里输入文字" },
        maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
        maxwidth: { type: Number, default: 750 },
        maxheight: { type: Number, default: 750 },
        background: { type: String, default: "" },
        toolbar: { type: Array, default: ['undo redo | bold italic underline strikethrough | forecolor backcolor fontsize | bullist numlist alignleft aligncenter alignright | hr link image axupimgs media table | blockquote removeformat code codesample charmap preview fullscreen']} 
    })
    let obj = reactive({
        html: props.value
    })
    let init = {
        base_url:"/tinymce", //若无这个，language就无法显示了
        // skin_url: '/tinymce/skins/ui/oxide', // 皮肤：这里引入的是public下的资源文件
        skin_url: '/tinymce/skins/ui/tinymce-5', // 皮肤：这里引入的是public下的资源文件
        language: 'zh-Hans',
        height: props.height,
        width: props.width,
        readOnly: props.readOnly,
        placeholder: props.placeholder,
        plugins: "code codesample autosave fullscreen table link charmap preview image axupimgs media wordcount lists advlist", //axupimgs
        toolbar: props.toolbar,
        autosave_interval: "20s", //自动保存
        font_size_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px',  //字体大小

        branding: false,  //tiny技术支持信息是否显示
        menubar: false, // 是否显示底部状态栏
        promotion: false, 
        // statusbar: false, //这是完全去掉状态栏
        elementpath: false,  //元素路径是否显示
        // convert_urls: false,
        // 初始化完成
        init_instance_callback: (editor) => {
            editor.getBody().style.fontSize = '14px';
        },
        images_upload_handler: function (blobInfo, succFun, failFun) {
            var file = blobInfo.blob();//转化为易于理解的file对象
            if (file.size > props.maxsize) {
                proxy.elMessageMixin(`不能超过${props.maxsize/(1024*1024)}M`, 'error')
                return
            }

            //检查完成，可以上传
            let formData = new FormData(); //这样可以给form参数了
            formData.append("type", file.type);
            formData.append("file", file);
            if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
            if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
            if (props.background != "") formData.append("background", props.background);

            proxy.$ajax({
                baseURL: "",
                url: proxy.$setting.globalUrl.uploadserver,
                data: formData,
                isUploadFile: true,
                bfLoading: false,
                timeout: 0,
                progress: p => { }
            }).then(res => {
                if(res.success){
                    succFun(`${proxy.$setting.globalUrl.upload}/${res.filename}`);
                }else{
                    failFun(`上传失败：${res.err}`)
                    // proxy.elMessageMixin("", 'error')
                }
            }).catch(e => failFun(e))
        },
        file_picker_types: 'file image media', //允许上传这些
        file_picker_callback: (callback, value, meta) => {
            let filetype = ""
            switch(meta.filetype){
                case 'image': filetype='.jpg,.jpeg,.png,.gif'; break;
                case 'media': filetype='.mp3,.mp4'; break;
                case 'file': break;
                default: break;
            }
            //模拟出一个input用于添加本地文件
            let input = document.createElement('input');
            input.setAttribute('type', 'file');
            if (filetype != "") input.setAttribute('accept', filetype);
            input.click();
            input.onchange = e => {
                let file = input.files[0]
                // console.log(file.size, props.maxsize)
                if (file.size > props.maxsize) {
                    proxy.elMessageMixin(`不能超过${props.maxsize/(1024*1024)}M`, 'error')
                    return
                }

                //检查完成，可以上传
                let formData = new FormData(); //这样可以给form参数了
                formData.append("type", file.type);
                formData.append("file", file);
                if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
                if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
                if (props.background != "") formData.append("background", props.background);

                // tinyMCE.activeEditor.setProgressState(true); //这一般用在禁用，但有弹出杠时，无效
                tinymce.DOM.doc.querySelector(".tox-dialog .tox-dialog__footer").prepend(document.createElement("span")) //最终只能用jquery的方式实现进度
                // console.log(tinymce.activeEditor.editorUpload)
                // var notification = tinymce.activeEditor.notificationManager.open({
                //     text: '上传中，请稍候',
                //     progressBar: true
                // });
                // console.log(notification)
                proxy.$ajax({
                    baseURL: "",
                    url: proxy.$setting.globalUrl.uploadserver,
                    data: formData,
                    isUploadFile: true,
                    bfLoading: false,
                    timeout: 0,
                    progress: p => {
                        // notification.progressBar.value(p.loaded / p.total * 100 | 0);
                        tinymce.DOM.doc.querySelector(".tox-dialog .tox-dialog__footer span").innerHTML = "上传中... "+(p.loaded / p.total * 100 | 0) + '%';
                    }
                }).then(res => {
                    // tinymce.activeEditor.notificationManager.close();
                    tinymce.DOM.doc.querySelector(".tox-dialog .tox-dialog__footer span").remove()
                    switch(meta.filetype){
                        case 'image': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {alt: file.name}); break;
                        case 'media': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {source2: file.name, poster: ''}); break;
                        case 'file': callback(`${proxy.$setting.globalUrl.upload}/${res.filename}`, {text: file.name}); break;
                        default: break;
                    }
                }).catch(() => tinymce.DOM.doc.querySelector(".tox-dialog .tox-dialog__footer span").remove())
            }
        }
    }
    watch( //里头改了通知外面
        () => obj.html,
        (val) => emit('update:value', val)
    )
    watch( //外面改了通知里面
        () => props.value,
        (val) => obj.html = val
    )
</script>

<style scoped lang="scss">
</style>